package com.example.icampusevent;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.example.icampusevent.jsonobjects.TimeQueryEvent;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.ListFragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class EventListFragment extends ListFragment {
	
	private ArrayList<TimeQueryEvent> eventList;
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
	}
	
	@Override
    public void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = new Intent(getActivity(), EventDetailActivity.class);
		intent.putExtra("EVENTID", eventList.get(position).getId());
		intent.putExtra("USERID", ((SearchActivity)getActivity()).getUserId());
		intent.putExtra("MODE", 0);
		startActivity(intent);
    }
	
	
	public void initEventList() {
		// Populate event list
        Calendar c = Calendar.getInstance();
        long startTime = c.getTimeInMillis();
        String url = "http://hamedaan.usc.edu:8080/team15/EventServlet?q=search&low=1&high=20&start=" 
                + startTime + "&end=-1&cat=ALL&key=";
        LoadEventListTask task = new LoadEventListTask();
        task.execute(new String[] { url });
	}
	
	
	public void updateEventList(ArrayList<String> categories, String keyword, long startTime) {
		String url = "http://hamedaan.usc.edu:8080/team15/EventServlet?q=search&low=1&high=50&start=" 
	            + startTime + "&end=-1";
		for(String cat : categories) {
			url += "&cat=" + cat;
		}
		url += "&key=" + keyword;
		LoadEventListTask task = new LoadEventListTask();
        task.execute(new String[] { url });
	}
	
	
	private class LoadEventListTask extends AsyncTask<String, Integer, Reader> {
	    protected Reader doInBackground(String... url) {
	    	InputStream source = retrieveStream(url[0]);
	 		if(source == null) return null;
	 		 
	 		Reader inputReader = new InputStreamReader(source);
	 		return inputReader;
	    }

	    protected void onPostExecute(Reader json) {
	    	Type listType = new TypeToken<ArrayList<TimeQueryEvent>>(){}.getType();
	 		Gson gson = new Gson();
			eventList = gson.fromJson(json, listType);
			setListAdapter(new EventListAdapter(getActivity(), eventList));
	    }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		return null;
	 	}
	}
	
	public void toast(String s) {
		CharSequence text = s;
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(getActivity(), text, duration);
		toast.show();
	}
}
